<?php
/**
 * Project: HTPHouDuan
 * User: xilibo
 * Date: 2018/1/26
 */

namespace app\common\library;

/**
* HTTP请求类
*/
class HttpRequest
{
    public static function doGetRequest($params)
    {
        $url = $params['url'];
        if (! empty($params['param'])){
            $url .= '?' . http_build_query($params['param']);
        }

        $result = self::curlRequest($url);

        return $result;
    }

    public static function doPostRequest($params)
    {
        $url = $params['url'];
        if (isset($params['param'])){
            $params = $params['param'];
        }

        $result = self::curlRequest($url, 'POST', $params);
        
        return $result;
    }

    public static function curlRequest($url, $method = 'GET', $params = [], $headers = [], $timeout = 5)
    {
        $method = strtoupper($method);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        @curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_POST, $method == 'POST');
        if ($method == 'POST' || $method == 'PUT'){
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
        }
        
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }
}